package com.home766.util;

import net.biz.Order;
import net.biz.Pageable;
import net.biz.util.ParamsUtil;
import org.apache.commons.collections.MapUtils;

import java.util.List;
import java.util.Map;

public class AppendSqlUtil {

	
	/**
	 * 
	 * @param params 参数map
	 * @param buffer StringBuffer
	 * @param include 模糊查询包含字符
	 * @param prefix 前缀
	 * @return
	 */
	public static StringBuffer appendSql(Map<String, Object> params, StringBuffer buffer, String include, String prefix){
		String tempPreFix="";
		if(!StringUtil.isNullOrSpace(prefix)){
			tempPreFix=prefix;
			tempPreFix+=".";
		}
		if(MapUtils.isNotEmpty(params)) {
			StringBuffer includeBuffer=null;
			String[] array=null;
			for(Map.Entry<String, Object> entry : params.entrySet()) {
				if(!StringUtil.isNullOrSpace(include)){
					if(null==includeBuffer){
						includeBuffer=new StringBuffer();
					}
					if(null==array){
						array= include.split(",");
					}
					if(checkKey(entry.getKey(),array)){
						includeBuffer.append(" and ").append(tempPreFix+entry.getKey()).append(" like :").append(entry.getKey());
						params.put(entry.getKey(), "%"+params.get(entry.getKey())+"%");
					}
				}else{
					buffer.append(" and ").append(tempPreFix+entry.getKey()).append(" = :").append(entry.getKey());
				}
			}
			if(includeBuffer!=null){
				buffer.append(includeBuffer);
			}
		}
		return buffer;
	}
	private static boolean checkKey(String key, String[] array){
		if(null==array){
			return false;
		}
		for(String str:array){
			if(key.indexOf(str)!=-1){
				return true;
			}
		}
		return false;
	}
	
	public static StringBuffer appendOrdSQL(Pageable pageable, StringBuffer buffer, String prefix){
		String tempPreFix="";
		if(!StringUtil.isNullOrSpace(prefix)){
			tempPreFix=prefix;
			tempPreFix+=".";
		}
		List<Order> orders= pageable.getOrders();
		if(!StringUtil.isNullOrSpace(pageable.getOrderProperty())&&(null==orders||orders.isEmpty())){
			buffer.append(ParamsUtil.SQL_ORDER_BY+tempPreFix+pageable.getOrderProperty()+" "+pageable.getOrderDirection().name());
		}
		if(null!=orders&&!orders.isEmpty()&&StringUtil.isNullOrSpace(pageable.getOrderProperty())){
			StringBuffer orderBuffer=new StringBuffer(ParamsUtil.SQL_ORDER_BY);
			for(Order o:orders){
				String direction="";
				if(null==o.getDirection()){
					direction= ParamsUtil.SQL_ORDER_BY_DESC;
				}else{
					direction=o.getDirection().name();
				}
				orderBuffer.append(tempPreFix+o.getProperty()+" "+direction+" , ");
			}
			String str=orderBuffer.toString();
			if(str.length()>2){
				str=str.substring(0,str.length()-1);
			}
			buffer.append(str);
		}
		return buffer;
	}
}
